package com.example.blog.util;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;


public class JDBCUtil {
    private static volatile MysqlDataSource dataSource  = null;
    private static final String URL = "jdbc:mysql://localhost:3306/servlet_blog?user=root&password=fjn.5006&useUnicode=true&characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true";

    /**
     * 获取数据源（多线程安全情况下） 懒汉式单例模式
     * @return
     */
    private static DataSource getDataSource(){
        if(dataSource == null){
            synchronized (JDBCUtil.class){
                if (dataSource == null){
                    //忘了初始化，导致报错，datasource为null
                    dataSource = new MysqlDataSource();
                    dataSource.setURL(URL);
                }
            }
        }
        return dataSource;
    }

    /**
     * 获取数据库连接
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }

    /**
     * 关闭数据库连接
     * @param connection
     */
    public static void close(Connection connection){
        if(connection == null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try {
            System.out.println(getConnection());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
